<template>
  <div style="margin-top: 20px">
    <ko-card :title="$t('business.workload.resource')">
      <table style="width: 98%" class="tab-table">
        <tr>
          <th scope="col" width="30%" align="left">
            <label>{{ $t("business.network.verbs") }}</label>
          </th>
          <th scope="col" width="30%" align="left">
            <label>{{ $t("business.workload.resource") }}</label>
          </th>
          <th scope="col" width="20%" align="left">
            <label>{{ $t("business.network.non_resource_url") }}</label>
          </th>
          <th scope="col" width="15%" align="left">
            <label>{{ $t("business.network.api_group") }}</label>
          </th>
          <th align="left" />
        </tr>
        <tr v-for="(row, index) in rules" v-bind:key="index">
          <td>
            <el-select
              v-model="row.verbs"
              multiple
              style="width: 100%"
              @change="changeVerbs(row)"
            >
              <el-option label="*" :value="'*'" />
              <el-option
                label="create"
                :value="'create'"
                :disabled="row.verbs[0] === '*'"
              />
              <el-option
                label="delete"
                :value="'delete'"
                :disabled="row.verbs[0] === '*'"
              />
              <el-option
                label="list"
                :value="'list'"
                :disabled="row.verbs[0] === '*'"
              />
              <el-option
                label="get"
                :value="'get'"
                :disabled="row.verbs[0] === '*'"
              />
              <el-option
                label="patch"
                :value="'patch'"
                :disabled="row.verbs[0] === '*'"
              />
              <el-option
                label="update"
                :value="'update'"
                :disabled="row.verbs[0] === '*'"
              />
              <el-option
                label="watch"
                :value="'watch'"
                :disabled="row.verbs[0] === '*'"
              />
            </el-select>
          </td>
          <td>
            <el-input
              v-model="resources[index]"
              :placeholder="$t('business.access_control.resource_helper')"
              @change="onResourceChange(row, index)"
            />
          </td>
          <td>
            <el-input
              v-model="nonResourceURLs[index]"
              :placeholder="$t('business.access_control.resource_helper')"
              @change="onChangeNonResourceUrls(row, index)"
            />
          </td>
          <td>
            <!--{{rules[index].apiGroups}}-->
            <el-select
              v-model="rules[index].apiGroups"
              multiple
              style="width: 100%"
            >
              <el-option
                v-for="(row, index) in groups"
                :key="index"
                :label="row.name"
                :value="row.name"
              />
            </el-select>
          </td>
          <td>
            <el-button
              type="text"
              style="font-size: 10px"
              @click="onRemoveSource(index)"
            >
              {{ $t("commons.button.delete") }}
            </el-button>
          </td>
        </tr>
        <tr>
          <td align="left">
            <el-button style="margin-top: 5px" @click="onAddSource()">
              {{ $t("commons.button.add")
              }}{{ $t("business.workload.resource") }}</el-button
            >
          </td>
        </tr>
      </table>
    </ko-card>
  </div>
</template>

<script setup lang="ts">
import KoCard from "@/views/domain/kubeHud/views/components/ko-card/index.vue";
import { useK8SApi } from "../../../api/k8s";
import { ref } from "vue";

const { apiServiceRepo } = useK8SApi();

type Prop = {
  cluster?: string;
  rulesArray?: any[];
};
const props = defineProps<Prop>();
const emit = defineEmits(["update:rulesArray"]);

const rules = ref<any[]>([]);
const resources = ref<any[]>([]);
const nonResourceURLs = ref<any[]>([]);
const groups = ref<any[]>([]);

const onRemoveSource = (index: number) => {
  rules.value.splice(index, 1);
  resources.value.splice(index, 1);
  nonResourceURLs.value.splice(index, 1);
};

const onAddSource = () => {
  rules.value.push({
    verbs: [],
    resources: [],
    nonResourceURLs: []
  });
  resources.value.push("");
  nonResourceURLs.value.push("");
};

const onResourceChange = (data: any, index: number) => {
  if (resources.value[index].indexOf(",") > 0) {
    data.resources = resources.value[index].split(",");
  } else {
    data.resources =
      resources.value[index] === "" ? [] : [resources.value[index]];
  }
  deleteAttributes(data);
};

const onChangeNonResourceUrls = (data: any, index: number) => {
  if (nonResourceURLs.value[index].indexOf(",") > 0) {
    data.nonResourceURLs = nonResourceURLs.value[index].split(",");
  } else {
    data.nonResourceURLs =
      nonResourceURLs.value[index] === "" ? [] : [nonResourceURLs.value[index]];
  }
  deleteAttributes(data);
};

const transformData = (src: any[], dist: any[]) => {
  dist.push(src.join(","));
};

const deleteAttributes = data => {
  if (data.nonResourceURLs?.length === 0 && data.resources?.length !== 0) {
    delete data.nonResourceURLs;
  }
  if (data.nonResourceURLs?.length !== 0 && data.resources?.length === 0) {
    delete data.resources;
  }
};

const changeVerbs = data => {
  if (data.verbs.findIndex(item => item === "*") > -1) {
    data.verbs = ["*"];
  }
};

const initData = () => {
  if (props.rulesArray && props.rulesArray.length > 0) {
    rules.value = props.rulesArray;
    rules.value.forEach(rule => {
      transformData(rule.resources, resources.value);
      transformData(rule.nonResourceURLs, nonResourceURLs.value);
    });
  } else {
    rules.value.push({
      verbs: [],
      resources: [],
      nonResourceURLs: []
    });
    resources.value.push("");
    nonResourceURLs.value.push("");
    emit("update:rulesArray", rules.value);
  }

  if (props.cluster) {
    apiServiceRepo.listApis(props.cluster).then(res => {
      groups.value = res.groups ?? [];
    });
  }
};
</script>

<style scoped></style>
